package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.oracle.zebrafreelytraveling.App;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.model.NaviInfoModel;
import com.oracle.zebrafreelytraveling.map.MapUtil;
import com.oracle.zebrafreelytraveling.map.overlay.BusRouteOverlay;
import com.oracle.zebrafreelytraveling.map.overlay.DrivingRouteOverlay;
import com.oracle.zebrafreelytraveling.map.overlay.RideRouteOverlay;
import com.oracle.zebrafreelytraveling.map.overlay.WalkRouteOverlay;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.fragment.BusSlideDailogFragment;
import com.oracle.zebrafreelytraveling.ui.fragment.ClassifyInfoFragment;
import com.oracle.zebrafreelytraveling.ui.fragment.NaviSlideDialogFragment;
import com.oracle.zebrafreelytraveling.ui.service.SuspendService;
import com.oracle.zebrafreelytraveling.utils.GsonUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by yydcnjjw on 2017/7/28.
 */

public class ClassifyTrafficActivity extends AppCompatActivity implements AMap.OnMyLocationChangeListener,
        Inputtips.InputtipsListener, SearchView.OnQueryTextListener,
        RouteSearch.OnRouteSearchListener , BusSlideDailogFragment.BusRouteListener{

    private Context mContext;

    private SearchView mPoiSearchView;
    private MenuItem mPlanMenu;
    private RecyclerView mLvPoiSearchInfo;
    private List<Tip> mPoiSearchInfoList;
    private CommonAdapter<Tip> mPoiSearchListAdapter;

    private List<Marker> markerList = new ArrayList<>();

    private Toolbar mToolbar;
    private ProgressDialog progDialog = null;// 搜索时进度条

    private MapUtil mapUtil;
    //当前位置信息
    private RegeocodeAddress regeocodeAddress;
    private MapView mMapView;
    //map地图
    private AMap mAMap;
    //定位蓝点
    private MyLocationStyle myLocationStyle;
    //逆地理编码
    private GeocodeSearch geocodeSearch;

    private RouteSearch routeSearch;
    private DriveRouteResult mDriveRouteResult;
    private RideRouteResult mRideRouteResult;
    private BusRouteResult mBusRouteResult;
    private WalkRouteResult mWalkRouteResult;

    //第一次定位的位置
    private LatLonPoint from;
    private LatLonPoint to;

    private boolean isAgainPlan = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traffic_classify);
        mContext = App.getContextObject();
        initView();
        mMapView.onCreate(savedInstanceState);
        if (mAMap == null) {
            mAMap = mMapView.getMap();
            mAMap.setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
                @Override
                public void onMarkerDragStart(Marker marker) {

                }

                @Override
                public void onMarkerDrag(Marker marker) {
                    marker.destroy();
                    markerList.remove(marker);
                    Log.d("marker", markerList.size()+"");
                }

                @Override
                public void onMarkerDragEnd(Marker marker) {

                }
            });
        }
        initMyLocationStyle();
        initGeocodeSearch();
        initPlan();
        NaviInfoModel model = UserUtil.getUserNaviModelList();
        if (model != null){
            showIsDisplayDialog(model);
        }

    }

    private void initDisplay(NaviInfoModel model){
        List<NaviInfoModel.bean> list = model.getNaviInfoModelList();
        for (int i = 0; i < list.size(); i++) {
            LatLng l = new LatLng(list.get(i).getLatitude(), list.get(i).getLongitude());
            Marker marker = mAMap.addMarker(addOptions(l, list.get(i).getTitle()));
            markerList.add(marker);
        }
    }

    private void showIsDisplayDialog(NaviInfoModel model){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.is_continue_navi));
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> initDisplay(model));
        builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.mipmap.cp_ic_back);
        mToolbar.setNavigationOnClickListener(v -> onBackPressed());
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mMapView = (MapView) findViewById(R.id.traffic_map);
        mLvPoiSearchInfo = (RecyclerView) findViewById(R.id.poi_search_info);

        poiSearchInfoListView();
    }

    private void poiSearchInfoListView() {
        mLvPoiSearchInfo.setLayoutManager(new LinearLayoutManager(this));
        mLvPoiSearchInfo.setItemAnimator(new DefaultItemAnimator());
        mPoiSearchInfoList = new ArrayList<>();
        initPoiSearchAdapter();
    }

    private MarkerOptions addOptions(LatLng latLng, String title){
        MarkerOptions options = new MarkerOptions();
        options.position(latLng);
        options.title(title);
        options.draggable(true);
        options.setFlat(true);
        return options;
    }

    private void initPoiSearchAdapter(){
        mPoiSearchListAdapter = new CommonAdapter<Tip>(this, R.layout.item_poi_search, mPoiSearchInfoList) {
            @Override
            protected void convert(ViewHolder holder, Tip tip, int position) {
                holder.setText(R.id.poi_search_info, tip.getName());
            }
        };
        mPoiSearchListAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                LatLonPoint latLonPoint = mPoiSearchInfoList.get(position).getPoint();
                LatLng latLng = MapUtil.convertToLatLng(latLonPoint);
                Marker marker = mAMap.addMarker(addOptions(latLng, mPoiSearchInfoList.get(position).getName()));
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
                if (markerList == null){
                    markerList = new ArrayList<>();
                }
                markerList.add(marker);
                mLvPoiSearchInfo.setVisibility(View.GONE);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLvPoiSearchInfo.setAdapter(mPoiSearchListAdapter);
    }

    /**
     * 初始化蓝点样式
     */
    private void initMyLocationStyle() {
        myLocationStyle = new MyLocationStyle();
        //连续定位、且将视角移动到地图中心点，
        // 定位点依照设备方向旋转，并且会跟随设备移动。
        // （1秒1次定位）默认执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.setMyLocationEnabled(true);
        mAMap.setOnMyLocationChangeListener(this);
    }

    private void initGeocodeSearch() {
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (regeocodeResult != null){
                    regeocodeAddress = regeocodeResult.getRegeocodeAddress();
                }
            }
            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
    }

    private void searchPoiInfo(String searchInfo) {
        if (regeocodeAddress == null){
            ToastUtil.showToast(getString(R.string.location_false));
            return;
        }
        InputtipsQuery inputtipsQuery = new InputtipsQuery(searchInfo, regeocodeAddress.getCity());
        inputtipsQuery.setCityLimit(true);
        Inputtips inputtips = new Inputtips(ClassifyTrafficActivity.this, inputtipsQuery);
        inputtips.setInputtipsListener(this);
        inputtips.requestInputtipsAsyn();
    }

    private void showPlanDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置路线规划");
        String[] plan = new String[]{"驾车出行规划", "步行出行规划", "公交出行规划", "骑行出行规划"};
        builder.setItems(plan, (dialog, which) -> startPlan(which));
        builder.show();
    }

    private void initPlan() {
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
    }

    private void startPlan(int which) {
        showProgressDialog();
        RouteSearch.FromAndTo fromAndTo;
        if ((fromAndTo = setFromAndTo()) == null) {
            //TODO 默认需要官方提供设计好的旅游路线
            ToastUtil.showToast(getString(R.string.not_location_design));
            dissmissProgressDialog();
            return;
        }
        switch (which) {
            case 0:
                RouteSearch.DriveRouteQuery driveRouteQuery = new RouteSearch.DriveRouteQuery(fromAndTo,
                        RouteSearch.DRIVING_MULTI_CHOICE_AVOID_CONGESTION_NO_HIGHWAY,
                        MapUtil.convertFromMarkerToLatLonPoint(markerList), null, "");
                routeSearch.calculateDriveRouteAsyn(driveRouteQuery);
                break;
            case 1:
                RouteSearch.WalkRouteQuery walkRouteQuery = new RouteSearch.WalkRouteQuery(fromAndTo);
                routeSearch.calculateWalkRouteAsyn(walkRouteQuery);
                break;
            case 2:
                RouteSearch.BusRouteQuery busRouteQuery = new RouteSearch.BusRouteQuery(fromAndTo,
                        RouteSearch.BusDefault, regeocodeAddress.getCity(), 0);
                routeSearch.calculateBusRouteAsyn(busRouteQuery);
                break;
            case 3:
                RouteSearch.RideRouteQuery rideRouteQuery = new RouteSearch.RideRouteQuery(fromAndTo);
                routeSearch.calculateRideRouteAsyn(rideRouteQuery);
                break;
        }

    }

    private RouteSearch.FromAndTo setFromAndTo() {
        //位置最远的
        LatLng fromLatLng = MapUtil.convertToLatLng(from);
        if (markerList.size() == 0){
            ToastUtil.showToast(getString(R.string.not_location_design));
            return null;
        }
        LatLng distanceMin = markerList.get(0).getPosition();
        for (int i = 1; i < markerList.size(); i++) {
            LatLng toLatLng2 = markerList.get(i).getPosition();
            float distance = AMapUtils.calculateLineDistance(fromLatLng, distanceMin);
            float distance2 = AMapUtils.calculateLineDistance(fromLatLng, toLatLng2);
            if (distance > distance2){
                distanceMin = markerList.get(i).getPosition();
            }
        }
        if (distanceMin != null) {
            to = MapUtil.convertToLatLonPoint(distanceMin);
            return new RouteSearch.FromAndTo(from, to);
        }
        return null;
    }

    private void startNaviActivity(LatLonPoint to, int position){
        NaviActivity.startNaviActivity(this, from, to, position);
        bindSuspendService();
        finish();
    }

    private void bindSuspendService(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,100);
            } else {
                Intent intent = new Intent(ClassifyTrafficActivity.this, SuspendService.class);
                startService(intent);
            }
        } else {
            Intent intent = new Intent(ClassifyTrafficActivity.this, SuspendService.class);
            startService(intent);
        }
    }
    /**
     * 展示规划好的导航列表
     * 可选择自定义导航也可以推荐导航
     */
    private void showNaviDialog(){
        if (markerList.size() == 0){
            ToastUtil.showToast(getString(R.string.not_location_design));
            return;
        }
        List<NaviInfoModel.bean> naviInfoModels = MapUtil.convertFromMarkerToNaviInfoModel(markerList);
        if (naviInfoModels.size() > 1){
            Collections.sort(naviInfoModels, (o1, o2) -> {
                LatLng latLng1 = new LatLng(o1.getLatitude(), o1.getLongitude());
                LatLng latLng2 = new LatLng(o2.getLatitude(), o2.getLongitude());
                double distance1 = AMapUtils.calculateLineDistance(MapUtil.convertToLatLng(from), latLng1);
                double distance2 = AMapUtils.calculateLineDistance(MapUtil.convertToLatLng(from), latLng2);
                return (int)(distance1 - distance2);
            });
        }
        NaviInfoModel model = new NaviInfoModel();
        model.setNaviInfoModelList(naviInfoModels);
        UserUtil.setUserNaviModelList(model);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.click_choose_navi));
        String[] naviName = new String[naviInfoModels.size()];
        for (int i = 0; i < naviInfoModels.size(); i++) {
            naviName[i] = naviInfoModels.get(i).getTitle();
            if (naviInfoModels.get(i).isNavied()){
                naviName[i] = naviName[i] + getString(R.string.receiving);
            }
        }
        builder.setItems(naviName, (dialog, which) -> {
            LatLonPoint l = new LatLonPoint(naviInfoModels.get(which).getLatitude(),
                    naviInfoModels.get(which).getLongitude());
            if (naviInfoModels.get(which).isNavied()){
                ToastUtil.showToast(getString(R.string.gone));
            }
            startNaviActivity(l, which);
        });
        builder.setPositiveButton(getString(R.string.recommend_navi), (dialog, which) -> {
            for (int i = 0; i < naviInfoModels.size(); i++) {
                if (naviInfoModels.get(i).isNavied()){
                    break;
                }
                LatLonPoint l = new LatLonPoint(naviInfoModels.get(i).getLatitude(),
                        naviInfoModels.get(i).getLongitude());
                startNaviActivity(l, i);
            }
        });
        builder.show();
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage(getString(R.string.cp_searching));
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }


    @Override
    public void onMyLocationChange(Location location) {
        from = new LatLonPoint(location.getLatitude(), location.getLongitude());
        RegeocodeQuery query = new RegeocodeQuery(from, 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    public static void startTrafficClassifyActivity(Activity activity) {
        Intent i = new Intent(activity, ClassifyTrafficActivity.class);
        activity.startActivity(i);
    }

    /************************************************setInputtipsListener************************/
    @Override
    public void onGetInputtips(List<Tip> list, int i) {
        if (mPoiSearchInfoList == null) {
            mPoiSearchInfoList = new ArrayList<>();
        } else {
            mPoiSearchInfoList.clear();
        }
        if (i == Constant.CODE_AMAP_SUCCESS) {
            for (Tip tip : list) {
                mPoiSearchInfoList.add(tip);
            }
            //如果searchAdapter不为空更新
            //否则new一个ArrayAdapter
            if (mPoiSearchListAdapter != null) {
                mPoiSearchListAdapter.notifyDataSetChanged();
                mLvPoiSearchInfo.setVisibility(View.VISIBLE);
            } else {
                initPoiSearchAdapter();
                mLvPoiSearchInfo.setVisibility(View.VISIBLE);
            }
        } else {
            ToastUtil.showToast(getString(R.string.search_false));
        }
    }

    /*******************************************OnQueryTextListener********************************/
    @Override
    public boolean onQueryTextSubmit(String query) {
        searchPoiInfo(query);
        mPoiSearchView.setQueryHint("");
        mLvPoiSearchInfo.setVisibility(View.VISIBLE);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if (newText.length() <= 0) {
            mLvPoiSearchInfo.setVisibility(View.GONE);
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_traffic_activity, menu);
        mPoiSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.searchPoi));
        mPoiSearchView.setOnQueryTextListener(this);
        mPoiSearchView.setSubmitButtonEnabled(true);
        mPoiSearchView.setQueryHint(getString(R.string.search));
        mPlanMenu = menu.findItem(R.id.plan);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navi:
                showNaviDialog();
                break;
            case R.id.plan:
                if (!isAgainPlan){
                    isAgainPlan = true;
                    showPlanDialog();
                } else {
                    item.setTitle(getString(R.string.plan));
                    markerList.clear();
                    mAMap.clear();
                    isAgainPlan = false;
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void clearMapAndAddMarkers() {
        mAMap.clear();
        ArrayList<MarkerOptions> markerOptionsList = new ArrayList<>();
        for (int i = 0; i < markerList.size(); i++) {
            markerOptionsList.add(markerList.get(i).getOptions());
        }
        mAMap.addMarkers(markerOptionsList, true);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
        dissmissProgressDialog();
        clearMapAndAddMarkers();
        if (i == Constant.CODE_AMAP_SUCCESS) {
            if (busRouteResult.getPaths().size() > 0) {
                mBusRouteResult = busRouteResult;
                BusSlideDailogFragment.newInstance(mBusRouteResult)
                        .showDialogFragment(getFragmentManager());
            } else if (busRouteResult != null && busRouteResult.getPaths() == null) {
                ToastUtil.showToast(getString(R.string.no_result));
            }
        } else {
            ToastUtil.showToast(getString(R.string.no_result));
        }
        mPlanMenu.setTitle(getString(R.string.again_plan));
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
        dissmissProgressDialog();
        clearMapAndAddMarkers();
        if (i == Constant.CODE_AMAP_SUCCESS) {
            if (driveRouteResult.getPaths().size() > 0) {
                mDriveRouteResult = driveRouteResult;
                final DrivePath drivePath = mDriveRouteResult.getPaths().get(0);
                DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                        mContext, mAMap, drivePath,
                        mDriveRouteResult.getStartPos(),
                        mDriveRouteResult.getTargetPos(), null);
                drivingRouteOverlay.setNodeIconVisibility(true);//设置节点marker是否显示
                drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
                drivingRouteOverlay.zoomToSpan();
                NaviSlideDialogFragment.newInstance(drivePath)
                        .showDialogFragment(getFragmentManager());
            } else if (driveRouteResult != null && driveRouteResult.getPaths() == null) {
                ToastUtil.showToast(getString(R.string.no_result));
            }
        } else {
            ToastUtil.showToast(getString(R.string.no_result));
        }
        mPlanMenu.setTitle(getString(R.string.again_plan));
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
        dissmissProgressDialog();
        clearMapAndAddMarkers();
        if (i == Constant.CODE_AMAP_SUCCESS) {
            if (walkRouteResult.getPaths().size() > 0) {
                mWalkRouteResult = walkRouteResult;
                final WalkPath walkPath = mWalkRouteResult.getPaths()
                        .get(0);
                WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(
                        this, mAMap, walkPath,
                        mWalkRouteResult.getStartPos(),
                        mWalkRouteResult.getTargetPos());
                if (walkRouteOverlay != null) {
                    walkRouteOverlay.removeFromMap();
                }
                walkRouteOverlay = new WalkRouteOverlay(
                        this, mAMap, walkPath,
                        mWalkRouteResult.getStartPos(),
                        mWalkRouteResult.getTargetPos());
                walkRouteOverlay.addToMap();
                walkRouteOverlay.zoomToSpan();
                NaviSlideDialogFragment.newInstance(walkPath)
                        .showDialogFragment(getFragmentManager());
            } else if (mWalkRouteResult != null && mWalkRouteResult.getPaths() == null) {
                ToastUtil.showToast(getString(R.string.no_result));
            }
        } else {
            ToastUtil.showToast(getString(R.string.no_result));
        }
        mPlanMenu.setTitle(getString(R.string.again_plan));
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        dissmissProgressDialog();
        clearMapAndAddMarkers();
        if (i == Constant.CODE_AMAP_SUCCESS) {
            if (rideRouteResult.getPaths().size() > 0) {
                mRideRouteResult = rideRouteResult;
                final RidePath ridePath = mRideRouteResult.getPaths().get(0);
                RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(
                        this, mAMap, ridePath,
                        mRideRouteResult.getStartPos(),
                        mRideRouteResult.getTargetPos());
                rideRouteOverlay.removeFromMap();
                rideRouteOverlay.addToMap();
                rideRouteOverlay.zoomToSpan();
                NaviSlideDialogFragment.newInstance(ridePath)
                        .showDialogFragment(getFragmentManager());
            } else if (rideRouteResult != null && rideRouteResult.getPaths() == null) {
                ToastUtil.showToast(getString(R.string.no_result));
            }
        } else {
            ToastUtil.showToast(getString(R.string.no_result));
        }
        mPlanMenu.setTitle(getString(R.string.again_plan));
    }

    @Override
    public void setBusRouteToMap(BusPath path, BusRouteResult mBusRouteResult) {
        BusRouteOverlay mBusrouteOverlay = new BusRouteOverlay(this, mAMap,
                path, mBusRouteResult.getStartPos(),
                mBusRouteResult.getTargetPos());
        mBusrouteOverlay.removeFromMap();
        mBusrouteOverlay.addToMap();
        mBusrouteOverlay.zoomToSpan();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    Intent intent = new Intent(ClassifyTrafficActivity.this, SuspendService.class);
                    startService(intent);
                }
            }else {
                ToastUtil.showToast("ACTION_MANAGE_OVERLAY_PERMISSION权限已被拒绝");
            }
        }

    }
}
